package com.whfc.iot.mach.client;

import com.whfc.iot.codec.CustomLengthFieldBasedFrameDecoder;
import com.whfc.iot.mach.codec.MachMsgDecoder;
import com.whfc.iot.mach.codec.MachMsgEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class EquipClient {

    public void connect(String host, int port) throws Exception {

        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new CustomLengthFieldBasedFrameDecoder(1024, 7, 2, -9, 0));
                    ch.pipeline().addLast(new IdleStateHandler(6, 0, 0, TimeUnit.MINUTES));
                    ch.pipeline().addLast(new MachMsgDecoder());
                    ch.pipeline().addLast(new MachMsgEncoder());
                    ch.pipeline().addLast(new EquipClientHandler());
                }
            });
            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }


}
